import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/common_loading_widget.dart';
import 'package:casdon/modules/recipe/application/notification/category_child_list_notifier.dart';
import 'package:casdon/modules/recipe/data/api/cook_model_api.dart';
import 'package:casdon/modules/recipe/ui/screen/category_recipe_list_screen.dart';
import 'package:casdon/modules/recipe/ui/widgets/tabbar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
@RoutePage()
class RecipeCategoryDetailScreen extends ConsumerStatefulWidget {
  final String title;
  final String id;

  const RecipeCategoryDetailScreen({
    super.key,
    required this.title,
    required this.id,
  });

  @override
  ConsumerState<RecipeCategoryDetailScreen> createState() =>
      _RecipeCategoryDetailtate();
}

class _RecipeCategoryDetailtate
    extends ConsumerState<RecipeCategoryDetailScreen>
    with TickerProviderStateMixin {
  final PageController _pageController = PageController();

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final tagsAsync = ref.watch(categoryChildNotifierProvider(widget.id));

    // 提前定义可用数据，避免 null 异常
    final tags = tagsAsync.value?.tags ?? [];
    final titleTags = tagsAsync.value?.titleTags ?? [];

    return Scaffold(
      backgroundColor: context.colorScheme.surface,
      appBar: CommonAppBar(title: widget.title),
      body: NestedScrollView(
        headerSliverBuilder: (context, innerBoxIsScrolled) {
          if (titleTags.length <= 1) {
            return [];
          }
          return [
            SliverToBoxAdapter(child: SizedBox(height: 16.h)),
            tagsAsync.when(
              data: (state) {
                return SliverPersistentHeader(
                  pinned: true,
                  delegate: _SliverTabBarDelegate(
                    Container(
                      alignment: Alignment.centerLeft,
                      padding: EdgeInsets.only(left: 12.w),
                      child: DynamicTabBar(
                        key: ValueKey(state.selectedIndex), // 确保动画正常
                        tabs: state.titleTags ?? [],
                        selectedIndex: state.selectedIndex,
                        onTap: (index) {
                          _pageController.animateToPage(
                            index,
                            duration: const Duration(milliseconds: 300),
                            curve: Curves.easeInOut,
                          );
                          ref
                              .read(
                                categoryChildNotifierProvider(
                                  widget.id,
                                ).notifier,
                              )
                              .updateSelectedIndex(index);
                        },
                      ),
                    ),
                  ),
                );
              },
              loading: () => const SliverToBoxAdapter(child: SizedBox.shrink()),
              error: (e, _) => SliverToBoxAdapter(child: SizedBox.shrink()),
            ),
          ];
        },
        body: tagsAsync.maybeWhen(
          data: (state) => PageView.builder(
            controller: _pageController,
            itemCount: state.tags.length,
            onPageChanged: (index) {
              ref
                  .read(categoryChildNotifierProvider(widget.id).notifier)
                  .updateSelectedIndex(index);
            },
            itemBuilder: (_, index) {
              final tag = state.tags[index];
              return CategoryRecipeListScreen(
                categoryId: tag.id,
                title: tag.title,
              );
            },
          ),
          orElse: () => const Center(child: CommonLoadingWidget()),
        ),
      ),
    );
  }
}

extension on List<ResponseCookModelApi> {
  get titleTags => null;
}

class _SliverTabBarDelegate extends SliverPersistentHeaderDelegate {
  final Widget _tabBar;

  _SliverTabBarDelegate(this._tabBar);

  @override
  double get minExtent => 48.h;
  @override
  double get maxExtent => 48.h;

  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
    return Container(
      color: Colors.transparent,
      child: Theme(
        data: Theme.of(context).copyWith(
          dividerColor: Colors.transparent,
          splashColor: Colors.transparent,
          highlightColor: Colors.transparent,
        ),
        child: Material(
          color: Colors.transparent,
          elevation: 0,
          child: _tabBar,
        ),
      ),
    );
  }

  @override
  bool shouldRebuild(_SliverTabBarDelegate oldDelegate) => true;
}
